<template>
	<view id="a-map-container" 
		:markers="markers" :change:markers="AMapInstance.reloadMarker"
		:lines="lines" :change:lines="AMapInstance.reloadLines">
		
	</view>
</template>

<script>
	import {ref} from 'vue'
	export default {
		props: ['markers', 'lines'],
		setup(props) {
			
			const showDetail = function(e) {
				
				uni.showModal({
					title: `${e.title||''}详情`,
					content: '位置：' + e.position + '\nJSON：' + JSON.stringify(e).substr(0,20) + '...'
				})
			}
			return {
				showDetail, ...props
			}
		
		}
	}
	
</script>

<script module="AMapInstance" lang="renderjs">
	import AMapLoader from '@amap/amap-jsapi-loader';
	import {MarkerIcon} from './../assets/Base64Markers.js'
	
	
	let Amap = null
	let map = null
	
	const SingleTaskType = {
		ReloadMarker: 1,
		ReloadLine: 2,
	}
	
	/**
	 * AMap是异步的，例如加载点位时可能还没加载完，可以先存起来
	 * @type {Map<String, Function()>}
	 */
	let singleAsyncTasks = new Map()
	
	let addedMarkers = []
	let addedLines = []
	
	export default {
		beforeMount() {
		},
		mounted() {
			AMapLoader.load({
			    "key": "68aae429918d9c1a46ba170e380cbd1d",              // 申请好的Web端开发者Key，首次调用 load 时必填
			    "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			    "plugins": [],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
			}).then((resp)=>{
				Amap = resp
			    map = new AMap.Map('a-map-container')
				
				// 加载完成处理任务
				singleAsyncTasks.forEach(task => task())
				singleAsyncTasks.clear()
				
			})
		},
		
		methods: {
			/**
			 * 重载点数据
			 * @param {Array<({position, title,icon,iconSize})>} markers
			 */
			reloadMarker(points) {
				
				if(!points) return
				
				const task = () => {
					addedMarkers && map.remove(addedMarkers)
					const markers = points.map(item => {
						const marker = new AMap.Marker({
						    position: new AMap.LngLat(...item.position),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
							icon: new AMap.Icon({
								image: MarkerIcon || item.icon,
								imageSize: item.iconSize || [36,36],
								offset: new AMap.Pixel(0, 0),
								anchor: 'bottom-center'	
							}), // 添加 Icon 图标 URL
						    title: item.title
						})
						this.bindDetaltPopup(marker, item)
						return marker
					})
					map.add(markers)
					addedMarkers = markers
				}
				// Amap不存在的话存起来
				if(Amap) {
					task()
				}else {
					singleAsyncTasks.set(SingleTaskType.ReloadMarker, task)
				}
			},
			/**
			 * 重载线数据
			 * @param {Object} lines
			 */
			reloadLines(lines) {
				
				if(!lines) return
				
				const task = () => {
					addedLines && map.remove(addedLines)
					lines = lines.map(item => {
						const line = new AMap.Polyline({
						    position: item.path.map(pos => new AMap.LngLat(...pos)),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
							...item
						})
						
						this.bindDetaltPopup(line, item)
						return line
					})
					map.add(lines)
					addedLines = lines
				}
				// Amap不存在的话存起来
				if(Amap) {
					task()
				}else {
					singleAsyncTasks.set(SingleTaskType.ReloadLine, task)
				}
				
			},
			
			/**
			 * 绑定默认弹窗 
			 * @param {Object} object 集合对象
			 * @param {Object} item 数据
			 */
			bindDetaltPopup(object, item) {
				if(!object.on) return
				const infoWindow = new AMap.InfoWindow({
				   isCustom: true,  //使用自定义窗体
				   content: this.createPopup(item, () => {
					   infoWindow.close()
				   }),  //传入 dom 对象，或者 html 字符串
				   offset: new AMap.Pixel(0, -10),
				   anchor: 'bottom-center',
				   closeWhenClickMap: true
				})
				let showInfo = false
				object.on('click', (e) => {
					if(!showInfo) {
						infoWindow.open(map, e.target.getPosition ? e.target.getPosition() : e.lnglat)	
						showInfo = true
					}else {
						showInfo = false
						infoWindow.close()
					}
				})
				
			},
			
			// 创建自定义popup
			createPopup(item, callback) {
				
				const info =  document.createElement('div')
				info.className = 'info'
				info.innerHTML = `位置: ${item.position || '非点另作处理'}`
				
				const infoButton = document.createElement('button')
				infoButton.className = 'info__btn'
				infoButton.onclick = () => {
					this.$ownerInstance.callMethod('showDetail', item)
					callback()
				}		
				infoButton.innerText = '详细信息'
				info.append(infoButton)
				return info
			}
		}
	}
</script>

<style scoped="false">
	#a-map-container {
		width: 100%;
		height: 100%;
	}
	
	>>> .amap-logo,
	>>> .amap-copyright {
		display: none !important;
	}
	
	>>> .amap-info-contentContainer {
		background: #fff;
		border: 2px solid #ddd;
		border-radius: .2em;
		padding: 1em;
	}
	>>> .amap-info-contentContainer .info {
		display: flex;
		flex-direction: column;
	}
	>>> .info__btn {
		margin-top: 4px;
	}
</style>